/* eslint-disable react/no-unused-state, no-plusplus */
import React, { Component } from "react";
import allConst from "./../../../../constants/allConst.js";
import apiData from "./../../../../constants/api.js";
import {
  reqRestaurantComment,
  handleRestaurantComment
} from "./../../../../httpserver/api/comment.js";

import {
  Table,
  Tab,
  Button,
  Grid,
  Pagination,
  Overlay,
  Feedback,
  Dialog
} from "@icedesign/base";
import IceContainer from "@icedesign/container";
import CommentSearch from "./../CommentSearch";
import doFilter from "./../../../../utils/doFilter";

import "./CommentTable.scss";
const Toast = Feedback.toast;
const TabPane = Tab.TabPane;
const { Row, Col } = Grid;

export default class CommentTable extends Component {
  static displayName = "CommentTable";

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      formValue: {},
      allTableData: [], //所有评价数据
      filterTableData: [], //筛选后的所有数据
      PageTableData: [], //当前页码展示的表格数据
      currentPage: 1,
      selComment: [], //选中的评论信息作者集合
      visible: false,
      tabSel: "全部", //菜系评价列表下固有筛选Tab的选择值
      searchResultDisable: true, //控制菜系评价列表下固有筛选Tab中的“搜索结果”项是否禁用
      rowSelection: {
        onChange: this.onChangeSel,
        selectedRowKeys: []
      }
    };
    // this.gotoSearch = this.gotoSearch.bind(this);
  }
  componentWillMount() {
    // 初始化调用接口请求所有评价数据
    this.getData();
  }
  formChange = value => {
    console.log("changed value", value);
    this.setState({
      formValue: value
    });
  };

  // 固有的筛选评价tab选项
  gotoFilter(key) {
    this.setState({
      tabSel: key,
      searchResultDisable: true
    });
    if (key === "全部") {
      this.getFilterPageData();
    } else {
      let obj = {
        reviewStatus: key
      };
      this.getFilterPageData(obj);
    }
  }
  // 点击搜索改变固有的筛选评价tab选项
  changeTabSel = (tabSel, searchResultDisable) => {
    this.setState({
      tabSel,
      searchResultDisable
    });
  };
  // 获取某页数据
  getPageData = currentPage => {
    let { filterTableData } = this.state;
    const pageSize = 10; //一页显示10条数据
    let newTableData = [];
    let start = (currentPage - 1) * pageSize;
    let end = start + pageSize;
    filterTableData.forEach((item, index) => {
      filterTableData[index].id = index + 1;
    });
    newTableData = filterTableData.slice(start, end);
    this.setState({
      PageTableData: newTableData
    });
  };

  //获取筛选后的数据
  getFilterPageData = obj => {
    let that = this;
    let { allTableData } = this.state;
    let newFilterTableData = [];
    if (obj) {
      let conditions = {
        chooses: []
      };
      for (let key in obj) {
        if (obj[key] || obj[key] === 0) {
          //obj[key] === 0 用来处理搜索栏中未审核的状态值
          let condition = {
            type: key,
            value: obj[key]
          };
          conditions.chooses.push(condition);
        }
      }
      newFilterTableData = doFilter(allTableData, conditions);
    } else {
      newFilterTableData = allTableData;
    }
    this.setState(
      {
        filterTableData: newFilterTableData,
        currentPage: 1
      },
      () => {
        that.getPageData(1);
      }
    );
  };

  getData = () => {
    // 调用接口请求所有评价数据
    let that = this;
    reqRestaurantComment()
      .then(res => {
        if (res.status === 1) {
          that.setState(
            {
              allTableData: res.data
            },
            () => {
              that.getFilterPageData();
            }
          );
        } else {
          Toast.show({
            type: "prompt",
            size: "large",
            style: {
              background: "rgb(48, 128, 254)"
            },
            content: `抱歉，服务器正在维护，请稍后再试！`
          });
        }
      })
      .catch(err => {
        console.log(err);
        resolve();
        Toast.show({
          type: "error",
          size: "large",
          style: {
            background: "rgb(48, 128, 254)"
          },
          content: `系统开了个小差，请稍后再试！`
        });
      });
  };

  // 点击图片变大显示
  // 控制遮罩显隐
  imgEnlarge(url) {
    this.setState(
      {
        imgEnlargeUrl: url
      },
      () => {
        this.setState({ visible: true });
      }
    );
  }
  onClose = reason => {
    this.setState({
      visible: false
    });
  };
  // 表格勾选数据的信息采集（indexArr表示选中数据的下标数组集合[1,2,3],dataAll表示选中的完整数据数组集合[{},{},{}]）
  onChangeSel = indexArr => {
    let { filterTableData, rowSelection } = this.state;
    let selComment = []; //选中的评论信息作者集合，后期传输至后端处理
    rowSelection.selectedRowKeys = indexArr;
    selComment = indexArr.map(item => {
      let evaluationId =
        filterTableData[item - 1].evaluationRestaurant.evaluationId; //获取选中的每条评论信息中的作者
      return evaluationId;
    });
    this.setState({
      selComment,
      rowSelection
    });
    // console.log(selComment);
  };

  // 分页事件处理
  handlePaginationChange = currentPage => {
    this.setState({
      currentPage
    });
    // console.log(currentPage);
    this.getPageData(currentPage);
  };

  // 点击发布或者回绝按钮
  commentExamine(i) {
    let { selComment, rowSelection } = this.state;
    let obj = {
      evaluationId: selComment, //要审核的餐厅评论的id数组集合
      reviewStatus: i //审核操作   1发布 2回绝
    };
    let selNum = selComment.length;
    if (selNum) {
      let oper = `发布`;
      if (i === 2) {
        oper = `回绝`;
      }
      Dialog.confirm({
        title: "温馨提示 ：",
        content: `确定${oper}选中的 ${selNum} 条餐厅评论`,
        onOk: () => {
          return new Promise(resolve => {
            // 在这里发送数据给后台，成功后先执行resolve(),在定时器中toast相应的信息（成功发布【回绝】10条数据），
            // 如果失败了也先执行resolve(),在定时器中toast相应的信息（系统开了个小差，请稍后再试！）;
            handleRestaurantComment(obj)
              .then(res => {
                if (res.status === 1) {
                  resolve();
                  setTimeout(() => {
                    Toast.show({
                      type: "success",
                      size: "large",
                      style: {
                        background: "rgb(48, 128, 254)"
                      },
                      content: `成功${oper}${selNum}条餐厅评论`
                    });
                    this.getData();
                    rowSelection.selectedRowKeys = [];
                    this.setState({
                      tabSel: "全部",
                      selComment: [],
                      rowSelection
                    });
                  }, 1000);
                } else {
                  resolve();
                  Toast.show({
                    type: "prompt",
                    size: "large",
                    style: {
                      background: "rgb(48, 128, 254)"
                    },
                    content: `抱歉，服务器正在维护，请稍后再试！`
                  });
                }
              })
              .catch(err => {
                console.log(err);
                resolve();
                Toast.show({
                  type: "error",
                  size: "large",
                  style: {
                    background: "rgb(48, 128, 254)"
                  },
                  content: `系统开了个小差，请稍后再试！`
                });
              });
          });
        }
      });
    } else {
      Toast.show({
        type: "prompt",
        size: "large",
        style: {
          background: "rgb(48, 128, 254)"
        },
        content: "请选择需要操作的餐厅评论 ！"
      });
    }
  }
  // 创建表格中评价内容的dom结构
  renderContent = (value, index, record) => {
    return <div>{decodeURIComponent(value)}</div>;
  };
  // 创建表格中评价图片列的dom结构
  renderCommentImg = (value, index, record) => {
    if (value === null) {
      value = [];
    }
    return (
      <div style={styles.tableImg}>
        {value.map(val => (
          <img
            src={apiData.imgUrl + val}
            alt=""
            style={styles.imgSize}
            onClick={() => {
              this.imgEnlarge(apiData.imgUrl + val);
            }}
            key={val}
          />
        ))}
      </div>
    );
  };
  // 创建表格中评价信息状态列的dom结构
  renderCommentState = (value, index) => {
    let background = "";
    let text = "";
    switch (value) {
      case 1:
        background = "rgb(32, 119, 255)";
        text = "已发布";
        break;
      case 2:
        background = "rgb(250, 112, 112)";
        text = "已回绝";
        break;
      case 0:
        background = "#666";
        text = "未审核";
        break;
    }
    return (
      <div
        style={{
          background,
          fontSize: 15,
          textAlign: "center",
          paddingTop: 5,
          paddingBottom: 3,
          color: "#fff",
          borderRadius: 6
        }}
      >
        {text}
      </div>
    );
  };
  render() {
    return (
      <div>
        <CommentSearch
          onChange={this.getFilterPageData}
          changeTabSel={this.changeTabSel}
        />
        <IceContainer title="餐厅评论列表">
          <Row wrap style={styles.headRow}>
            <Col l="12">
              <div
                key="capsule"
                style={styles.fusionDemoItem}
                className="capsule"
              >
                <Tab
                  type="capsule"
                  size="small"
                  activeKey={this.state.tabSel}
                  onChange={key => {
                    this.gotoFilter(key);
                  }}
                >
                  {allConst.tabs.map(tab => (
                    <TabPane
                      tab={tab.tab}
                      disabled={
                        tab.key === "搜索结果" && this.state.searchResultDisable
                      }
                      key={tab.key}
                    />
                  ))}
                </Tab>
              </div>
            </Col>
            <Col l="12" style={styles.center}>
              <Button
                type="normal"
                onClick={() => {
                  this.commentExamine(1);
                }}
                style={{ ...styles.button, background: "#2077FF" }}
              >
                发布
              </Button>
              <Button
                type="normal"
                onClick={() => {
                  this.commentExamine(2);
                }}
                style={{
                  ...styles.button,
                  marginLeft: 10,
                  background: "#FA7070"
                }}
              >
                回绝
              </Button>
            </Col>
          </Row>
          <Table
            dataSource={this.state.PageTableData}
            rowSelection={this.state.rowSelection}
          >
            <Table.Column title="序号" dataIndex="id" width={60} />
            <Table.Column title="作者" dataIndex="user.userName" width={110} />
            <Table.Column
              title="内容"
              cell={this.renderContent}
              dataIndex="evaluationRestaurant.evaluationContent"
              width={320}
            />
            <Table.Column
              title="图片"
              cell={this.renderCommentImg}
              dataIndex="evaluationRestaurant.evaluationPhotoList"
              width={130}
            />
            <Table.Column
              title="状态"
              cell={this.renderCommentState}
              dataIndex="evaluationRestaurant.reviewStatus"
              width={80}
            />
            <Table.Column
              title="发表时间"
              dataIndex="evaluationRestaurant.evaluationDate"
              width={80}
            />
          </Table>
          <Pagination
            style={styles.pagination}
            current={this.state.currentPage}
            total={this.state.filterTableData.length}
            onChange={this.handlePaginationChange}
          />
          <Overlay
            visible={this.state.visible}
            className="overlay"
            hasMask
            // disableScroll
            align="cc cc"
            safeNode={() => this.refs.target}
            onRequestClose={this.onClose.bind(this)}
          >
            <img
              alt=""
              className="overlay-img"
              src={this.state.imgEnlargeUrl}
            />
          </Overlay>
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  headRow: {
    marginBottom: "10px"
  },
  icon: {
    color: "#2c72ee",
    cursor: "pointer"
  },
  fusionDemoItem: {
    margin: 0
  },
  deleteIcon: {
    marginLeft: "20px"
  },
  center: {
    textAlign: "right"
  },
  tableImg: {
    display: "flex",
    flexWrap: "wrap"

    // justifyContent: "space-between"
  },
  imgSize: {
    display: "block",
    marginRight: "5px",
    marginBottom: "5px",
    width: 60,
    height: 60
  },
  button: {
    zIndex: "1000",
    color: "#fff",
    cursor: "pointer"
  },
  pagination: {
    marginTop: "20px",
    textAlign: "right"
  }
};
